﻿using UnityEngine;
/// <summary>
/// Collider碰撞扩展
/// </summary>
public static class SFColliderExtendEngine
{
    /// <summary>
    /// 将指定MeshCollider转换为反面碰撞
    /// </summary>
    /// <param name="_meshCollider">MeshCollider</param>
    /// <returns>反面MeshCollider</returns>
    public static MeshCollider ConvertReverseSide(this MeshCollider _meshCollider)
    {
        var rstMesh = _meshCollider.sharedMesh;
        var normals = rstMesh.normals;
        for (int i = 0; i < normals.Length; ++i)
        {
            normals[i] = -normals[i];
        }
        rstMesh.normals = normals;

        for (int i = 0; i < rstMesh.subMeshCount; ++i)
        {
            int[] triangles = rstMesh.GetTriangles(i);
            for (int j = 0; j < triangles.Length; j += 3)
            {
                int temp = triangles[j];
                triangles[j] = triangles[j + 1];
                triangles[j + 1] = temp;
            }
            rstMesh.SetTriangles(triangles, i);
        }
        _meshCollider.sharedMesh = rstMesh;
        return _meshCollider;
    }

    /// <summary>
    /// 向指定MeshCollider添加反面碰撞
    /// </summary>
    /// <param name="_meshCollider">MeshCollider</param>
    /// <returns>反面MeshCollider</returns>
    public static MeshCollider AddReverseSide(this MeshCollider _meshCollider)
    {
        var mesh = GameObject.Instantiate(_meshCollider);
        var result = _meshCollider.gameObject.AddComponent<MeshCollider>();
        result.sharedMesh = mesh.ConvertReverseSide().sharedMesh;
        return result;
    }
}
